import { DocumentObject, Types } from '@amcax/base';
import { addPlane2GeomBox } from './addPlane2GeomBox';
import { unsortedTreeNodes } from '../assembly-funcs';
import { IAssemblyDocTreeNodeCAD } from '../types';
import { addFrame2GeomBox } from './addFrame2GemoBox';
import { ctx2 } from '@app-base/module';

/**
 * @description geomBox 类型分发层
 * 所有在装配的新添加坐标系、平面 原本来自于零件的东西都会被添加到 geomBox中
 * 在这里做个解耦 去处理各个类型
 */
const addEntireGeomBox = (
  rootObject: DocumentObject,
  docTreeRoot: IAssemblyDocTreeNodeCAD,
) => {
  const geomBoxNode = createGeomBoxNode(rootObject, docTreeRoot);

  rootObject.children.forEach((part) => {
    switch (part.type) {
      case Types.PLANE:
        addPlane2GeomBox(part, geomBoxNode);
        break;
      case Types.FRAME:
        addFrame2GeomBox(part, geomBoxNode);
        break;
    }
  });

  ctx2.requestRender();
  ctx2.viewer.sceneSetup.updatePixelBuffer();
  const oldIndex = unsortedTreeNodes.findIndex(
    (n) => n.key === geomBoxNode.key,
  );

  if (oldIndex !== -1) {
    unsortedTreeNodes.splice(oldIndex, 1);
  }
  unsortedTreeNodes.push(geomBoxNode);
};

function createGeomBoxNode(
  rootObject: DocumentObject,
  docTreeRoot: IAssemblyDocTreeNodeCAD,
): IAssemblyDocTreeNodeCAD {
  const geomBoxNode: IAssemblyDocTreeNodeCAD = {
    key: rootObject.dxid,
    title: rootObject.label || '几何体',
    type: Types.GeomBox,
    parent: docTreeRoot,
    visible: rootObject.visibility,
    originalObj: rootObject,
    recursivelyVisible: true,
    collectionUUID: '',
    version: 0,
    children: [],
    documentInfo: docTreeRoot.documentInfo,
  };
  return geomBoxNode;
}

export { addEntireGeomBox };
